//
//  WCNOrderCategoryTableVC.m
//  WCN
//
//  Created by 杨鑫 on 15/7/8.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNOrderCategoryTableVC.h"
#import "WCNOrderDetailVC.h"
//
#import "MJRefresh.h"
#import "WCNOrderTCell.h"
#import "NoRecordsView.h"
//
#import "WCDefaultManager.h"
#import "WCNetworkAccessManager.h"
#import "WCCoreDataStore.h"
#import "WCImageManager.h"
//
#import "Macros.h"
#import "Constants.h"
#import "NSString+Utilities.h"
//#import "ChatViewController.h"
//#import "ChatManager.h"

static NSString *cellId = @"WCNOrderTCell";
static NSNumber *rows;

@interface WCNOrderCategoryTableVC () <UITableViewDataSource, UITableViewDelegate>

{
    NSInteger _pageNum;
    NSArray *_conversations;
    
}
@property (strong, nonatomic) NSMutableArray *orders;
@property (strong, nonatomic) NSDate *refreshTime;

@end

@implementation WCNOrderCategoryTableVC

+ (void)load
{
    rows = [NSNumber numberWithInt:10];
}

- (instancetype)init
{
    return [self initWithCategory:_catetory];
}

- (instancetype)initWithCategory:(int)category
{
    self = [super init];
    if (self) {
        _catetory = category;
        
        _orders = [NSMutableArray new];
        
        [self loadView];
        //        [self registerNotifications];
    }
    return self;
}

- (void)loadView
{
    _pageNum = 1;
    UITableView *tableView = [[UITableView alloc] init];
    self.tableView = tableView;
    tableView.backgroundColor = kAppBg;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.rowHeight = 135;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 13)];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    __weak typeof(self) weakSelf = self;
    [tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf refresh];
    }];
}

- (void)viewWillShow
{
    //    [self loadAllConversations];
    [self.tableView.header beginRefreshing];
    
}
////加载所有会话
//- (void)loadAllConversations
//{
//    _conversations = [[EaseMob sharedInstance].chatManager conversations];
//
//}
// 得到未读消息条数
//- (NSInteger)unreadMessageCountByConversation:(EMConversation *)conversation
//{
//    NSInteger ret = 0;
//    ret = conversation.unreadMessagesCount;
//
//    return  ret;
//}
#pragma mark - IChatMangerDelegate

-(void)didUnreadMessagesCountChanged
{
    [self.tableView.header beginRefreshing];
}

#pragma mark - registerNotifications
//-(void)registerNotifications{
//    [self unregisterNotifications];
//    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
//}
//
//-(void)unregisterNotifications{
//    [[EaseMob sharedInstance].chatManager removeDelegate:self];
//}

//- (void)dealloc{
//    [self unregisterNotifications];
//}


- (void)viewDidShow
{
    if (![self.tableView.header isRefreshing]) {
        if (!self.refreshTime) {
            [self.tableView.header beginRefreshing];
        } else {
            NSDate *currrent = [NSDate date];
            if ([currrent timeIntervalSinceDate:self.refreshTime] > kUrlCD/30) {
                [self.tableView.header beginRefreshing];
            }
        }
    }
}

- (void)refreshTable
{
    if (![self.tableView.header isRefreshing]) {
        [self.tableView.header beginRefreshing];
    }
}

// 清空数据源
- (void)resetData
{
    [self.orders removeAllObjects];
    _pageNum = 0;
    self.refreshTime = nil;
    
    [self.tableView reloadData];
}

- (void)addFooterRefreshMode
{
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    self.tableView.footer.automaticallyRefresh = NO;
}

#pragma mark - others
//"nurseId": 15,
//"category": 1,
//"page": 1,   ----pageNum
//"rows": 2    ---pageSize

- (void)refresh
{
    _pageNum =1;
    Account *account = [[WCDefaultManager shareMg] account];
    if (!account) {
        return;
    }
    NSDictionary *params = @{@"nurseId":account.stringId,
                             @"category": @(self.catetory),
                             @"page": @(_pageNum),
                             @"rows": rows,
                             };
    NSString *url ;
    url =@"nursing/order/list";
    
    [[WCNetworkAccessManager sharedMg] POST:url parameters:params success:^(NSDictionary *result){
        self.refreshTime = [NSDate date];
        
        NSDictionary *page = result[@"data"];
        
        
        [self.orders removeAllObjects];
        for (NSDictionary *orderDict in page[@"result"]) {
            Order *order =[[Order alloc] init];
            order.nursingOrder_Status =[[NursingOrderStatus alloc]init];
            [order.nursingOrder_Status setValuesForKeysWithDictionary:orderDict[@"nursingOrderStatus"]];
            
            
            order.service_Type =[[ServiceType alloc] init];
            [order.service_Type setValuesForKeysWithDictionary:orderDict[@"serviceType"]];
            
            [order setValuesForKeysWithDictionary:orderDict];
            [self.orders addObject:order];
        }
        
        
        if (self.orders.count == 0) {
            self.tableView.tableHeaderView = [[NoRecordsView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 180)];
        } else {
            self.tableView.tableHeaderView = nil;
        }
        [self.tableView reloadData];
        
        //        _pageNum = [page[@"currentPage"] intValue];
        if ([page[@"totalPage"] intValue] > 1) {
            [self addFooterRefreshMode];
        }
    } failure:nil netError:nil always:^{
        [self.tableView.header endRefreshing];
    }];
}

- (void)loadMore
{
    _pageNum ++;
    Account *account = [[WCDefaultManager shareMg] account];
    NSDictionary *params = @{@"nurseId": account.stringId,
                             @"category": @(self.catetory),
                             @"page": @(_pageNum),
                             @"rows": rows};
    
    NSString *url ;
    url =@"nursing/order/list";
    
    [[WCNetworkAccessManager sharedMg] POST:url parameters:params success:^(NSDictionary *result){
        NSDictionary *page = result[@"data"];
        for (NSDictionary *orderDict in page[@"result"]) {
            Order *order =[[Order alloc] init];
            NursingOrderStatus *orderStatus =[[NursingOrderStatus alloc]init];
            [orderStatus setValuesForKeysWithDictionary:orderDict[@"nursingOrderStatus"]];
            order.nursingOrder_Status =orderStatus;
            
            ServiceType *serviceType =[[ServiceType alloc] init];
            [serviceType setValuesForKeysWithDictionary:orderDict[@"serviceType"]];
            order.service_Type =serviceType;
            [order setValuesForKeysWithDictionary:orderDict];
            [self.orders addObject:order];
        }
        
        
        [self.tableView reloadData];
        
        //        _pageNum = [page[@"currentPage"] intValue];
        if ([page[@"totalPage"] intValue] == _pageNum) {
            [self.tableView removeFooter];
            [self.tableView.footer removeFromSuperview];
        }
    } failure:nil netError:nil always:^{
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    }];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Order *order =self.orders[indexPath.row];
    WCNOrderDetailVC *vc = [[WCNOrderDetailVC alloc] init];
    vc.orderId = order.orderId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCNOrderTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    Order *order = self.orders[indexPath.row];
    
    
    cell.patientAvatarId = order.patientAvatarFileId;
    [cell configWithOrder:order withCatorgery:self.catetory withConversations:_conversations];
    weakSelf_define;
    cell.chatBlock = ^(NSInteger leftMeetTime){
        
        //        [weakSelf jumpToChatViewWithOrder:order withLeftMeetingTime:leftMeetTime];
        
    };
    
    return cell;
}

//- (void)jumpToChatViewWithOrder:(Order *)order withLeftMeetingTime:(NSInteger)leftTime
//
//{
//    if (![[ChatManager sharedChatManager] isLoginSucess]) {
//        Log(@"可能因为登陆出问题,环信当前不在登陆状态");
//        return;
//    }
//
//    NSString *chaterAccount =[NSString stringWithFormat:@"patient_%@",order.patientAccountMobile];
//    ChatViewController *vc =[[ChatViewController alloc] initWithConversationChatter:chaterAccount conversationType:eConversationTypeChat];
//
//    vc.title =order.patientName;
//     vc.meetingStatue =order.onlineConsultationStatus;
//    vc.meetingTime =[NSString stringWithFormat:@"%i",leftTime];
////    vc.nurseHeadViewStringId =order.nurseAvatarFileId;
////    vc.patientHeadViewStringId =order.patientAvatarFileId;
//
//    [self.navigationController pushViewController:vc animated:YES];
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.orders.count;
}

@end
